package com.icebergteam.resumemaster.resume_data;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.icebergteam.resumemaster.profile_data.Parser;
import com.icebergteam.resumemaster.utils.Serializable;

public class Field implements Serializable{
	// Constants
	private final String LABEL_STR_ID	= "Label";
	private final String VALUE_STR_ID	= "Value";
	// Members
	private String tagName;			// Tag name in XML file
	private int labelId;			// Android string id
	private String value;			// Contains value
	
	public Field() {
		setTagName("Empty");
		setLabelId(-1); // TODO create android string value and assign it here
		setValue("Empty");
	}
	
	public Field(String tagName, int displayedTagName) {
		this.setTagName(tagName);
		this.setLabelId(labelId);
		this.setValue("Empty");
	}
	
	public Field(String tagName, int displayedTagName, String value) {
		this.setTagName(tagName);
		this.setLabelId(labelId);
		this.setValue(value);
	}

	public String getTagName() {
		return tagName;
	}

	public void setTagName(String tagName) {
		this.tagName = tagName;
	}

	public int getLabelId() {
		return labelId;
	}
	
	public void setLabelId(int labelId) {
		this.labelId = labelId;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
	
	private static String getTagValue(String sTag, Element eElement) {
		NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
		Node nValue = (Node) nlList.item(0);
		return nValue.getNodeValue();
	}

	public boolean serialize(Node node) {
		// Get Document instance
		Document doc = Parser.getInstance().getDocument();
		// Create elements
		Element labelNode	= doc.createElement(LABEL_STR_ID);
		Element valueNode	= doc.createElement(VALUE_STR_ID);
		// Append values
		labelNode.appendChild(doc.createTextNode( Integer.toString(labelId)) );
		valueNode.appendChild(doc.createTextNode(value));
		// Append data to parent node
		node.appendChild(labelNode);
		node.appendChild(valueNode);
		
		return true;
	}

	public boolean deserialize(Node node) {
		try {
			// Cast node to Element
			Element element = (Element) node;
			// Get values
			labelId	= Integer.parseInt( getTagValue(LABEL_STR_ID, element) );
			value	= getTagValue(VALUE_STR_ID, element);
		}
		catch(Exception e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
}
